using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO.IsolatedStorage;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;
using System.Runtime.Serialization;

namespace JoinMe
{
    class IsolatedStorage
    {
        public static bool VerifyStore()
        {
            bool result = false;
            try
            {
                IsolatedStorageFileStream stream = new IsolatedStorageFileStream("ip.c", System.IO.FileMode.Open, IsolatedStorageFile.GetUserStoreForApplication());
                stream.Close();
                result = true;
            }
            catch (FileNotFoundException)
            {
                result = false;
            }
            return result;
        }

        public static IPEndPoint GetIPEndPoint()
        {
            IsolatedStorageFileStream stream = new IsolatedStorageFileStream("ip.c", FileMode.Open, IsolatedStorageFile.GetUserStoreForApplication());
            BinaryFormatter bf = new BinaryFormatter();
            IPEndPoint endPoint = bf.Deserialize(stream) as IPEndPoint;
            stream.Close();
            return endPoint;
        }

        public static void SetIPEndPoint(IPEndPoint address)
        {
            IsolatedStorageFileStream stream = new IsolatedStorageFileStream("ip.c", FileMode.Create, IsolatedStorageFile.GetUserStoreForApplication());
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(stream, address);
            stream.Close();
        }

        public static IPEndPoint DecryptIPEndPoint(string password)
        {
            RijndaelManaged rm = new RijndaelManaged();
            byte[] pass = Convert.FromBase64String(password.PadRight(32, '1'));
            StreamReader sr = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "ip.enc");
            int lenIV = sr.BaseStream.ReadByte();
            byte[] IV = new byte[lenIV];
            sr.BaseStream.Read(IV, 0, lenIV);
            ICryptoTransform ct = rm.CreateDecryptor(pass, IV);
            CryptoStream cs = new CryptoStream(sr.BaseStream, ct, CryptoStreamMode.Read);
            try
            {
                BinaryFormatter bf = new BinaryFormatter();
                IPEndPoint endPoint = bf.Deserialize(cs) as IPEndPoint;
                return endPoint;
            }
            catch (Exception)
            {
                // the password is incorrect
                throw;
            }
        }
    }
}
